<!-- AI智能排班对话框组件 -->
<template>
  <el-dialog
    v-model="dialogVisible"
    title="AI智能排班"
    width="900px"
    :destroy-on-close="true"
  >
    <div class="ai-schedule-generator">
      <!-- 左右布局 -->
      <div class="ai-layout">
        <!-- 左侧：AI对话区域 -->
        <div class="ai-chat-section">
          <div class="section-header">
            <h3>AI排班助手</h3>
            <el-tag type="info">DeepSeek</el-tag>
          </div>

          <div class="chat-container">
            <!-- AI对话消息列表 -->
            <div class="message-list" ref="messageListRef">
              <div
                v-for="(message, index) in chatMessages"
                :key="index"
                :class="['message-item', message.role]"
              >
                <div class="message-avatar">
                  <el-avatar v-if="message.role === 'assistant'" :size="32">
                    🤖
                  </el-avatar>
                  <el-avatar
                    v-else
                    :size="32"
                    style="background-color: #1890ff"
                  >
                    👤
                  </el-avatar>
                </div>
                <div class="message-content">
                  <div
                    class="message-text"
                    v-html="formatMessage(message.content)"
                  ></div>
                  <div class="message-time">
                    {{ formatTime(message.timestamp) }}
                  </div>
                </div>
              </div>

              <!-- 加载状态 -->
              <div v-if="loading" class="message-item assistant">
                <div class="message-avatar">
                  <el-avatar :size="32">🤖</el-avatar>
                </div>
                <div class="message-content">
                  <div class="message-text">
                    <div class="typing-indicator">
                      <span></span>
                      <span></span>
                      <span></span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 输入区域 -->
            <div class="input-section">
              <div class="ai-loading" v-if="loading">
                AI思考中...点击发送按钮停止输出
              </div>
              <el-input
                v-model="userInput"
                type="textarea"
                :rows="2"
                placeholder="请描述您的排班需求，例如：为张三医生生成下周的门诊和病房排班"
                :disabled="loading"
                @keydown.enter.exact.prevent="handleSendMessage"
                resize="none"
              />
              <div class="input-actions">
                <div class="ds-button-area">
                  <div v-if="!loading" class="send-area" @click="handleSendMessage">
                    <div class="ds-icon">
                      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024">
                        <path fill="currentColor" d="m64 448 832-320-128 704-446.08-243.328L832 192 242.816 545.472zm256 512V657.024L512 768z"></path>
                      </svg>
                    </div>
                  </div>
                  <div v-else class="send-area" @click="stopOutput">
                    <div class="ds-icon-stop"></div>
                  </div>
                </div>
                <el-button @click="clearChat"> 清空对话 </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧：生成结果确认区域 -->
        <div class="result-section">
          <div class="section-header">
            <h3>排班结果</h3>
            <el-tag :type="resultStatus.type">{{ resultStatus.text }}</el-tag>
          </div>

          <div class="result-content">
            <!-- 初始状态提示 -->
            <div v-if="!generatedData" class="empty-state">
              <el-icon size="48" color="#C0C4CC"><ChatRound /></el-icon>
              <p>请先与AI助手对话描述您的排班需求</p>
            </div>

            <!-- 生成结果预览 -->
            <div v-else class="result-preview">
              <div class="preview-header">
                <h4>生成的排班数据</h4>
                <el-tag type="success">已生成</el-tag>
              </div>

              <div class="preview-content">
                <el-descriptions :column="1" border size="small">
                  <el-descriptions-item label="排班数量">
                    {{ generatedData.instances?.length || 0 }} 条
                  </el-descriptions-item>
                  <el-descriptions-item label="覆盖策略">
                    {{
                      formatOverwriteStrategy(generatedData.overwriteStrategy)
                    }}
                  </el-descriptions-item>
                  <el-descriptions-item label="生成时间">
                    {{ formatTime(new Date()) }}
                  </el-descriptions-item>
                </el-descriptions>

                <!-- 排班列表预览 -->
                <div class="schedule-preview">
                  <h5>排班预览</h5>
                  <div class="preview-list">
                    <div
                      v-for="(
                        instance, index
                      ) in generatedData.instances?.slice(0, 5)"
                      :key="index"
                      class="preview-item"
                    >
                      <div class="preview-info">
                        <span class="staff-name">{{
                          instance.staff_name
                        }}</span>
                        <span class="schedule-date">{{
                          instance.schedule_date
                        }}</span>
                        <el-tag size="small">{{
                          formatTimeSlot(instance.time_slot_code)
                        }}</el-tag>
                      </div>
                    </div>
                    <div
                      v-if="generatedData.instances?.length > 5"
                      class="preview-more"
                    >
                      还有 {{ generatedData.instances.length - 5 }} 条排班...
                    </div>
                  </div>
                </div>
              </div>

              <!-- 确认操作 -->
              <div class="confirm-actions">
                <el-alert
                  title="请确认生成的排班数据"
                  description="确认后将提交到系统并生成实际的排班安排"
                  type="warning"
                  show-icon
                  :closable="false"
                />
                <div class="action-buttons">
                  <el-button @click="handleRegenerate">重新生成</el-button>
                  <el-button
                    type="primary"
                    @click="handleConfirm"
                    :loading="confirmLoading"
                  >
                    确认生成排班
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import {
  ref,
  reactive,
  computed,
  watch,
  nextTick,
  defineProps,
  defineEmits,
} from "vue";
import { ElMessage } from "element-plus";
import { ChatRound } from "@element-plus/icons-vue";

// ================ 传入属性数据为AI智能排班提供真实数据基础 ==================
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  // 新增：传入系统数据
  departmentOptions: {
    type: Array,
    default: () => [],
  },
  staffTypeOptions: {
    type: Array,
    default: () => [],
  },
  timeSlotOptions: {
    type: Array,
    default: () => [],
  },
  scheduleTypeOptions: {
    type: Array,
    default: () => [],
  },
  allStaffList: {
    type: Array,
    default: () => [],
  },
  currentScheduleInstances: {
    type: Array,
    default: () => [],
  },
  departmentList: {
    type: Array,
    default: () => [],
  },
  timeSlotList: {
    type: Array,
    default: () => [],
  },
  scheduleTypeList: {
    type: Array,
    default: () => [],
  },
  scheduleTemplates: {  // 新增：排班模板数据
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(["update:visible", "confirm", "cancel"]);

// ==================== 组件状态 ====================
const loading = ref(false);
const confirmLoading = ref(false);
const userInput = ref("");
const messageListRef = ref(null);

// ==================== AI流式响应相关状态 ====================
const isStoppedByUser = ref(false);
const aiResponseBuffer = ref("");
const aiStreamReader = ref(null);

// ==================== 聊天数据 ====================
const chatMessages = ref([
  {
    role: "assistant",
    content:
      "您好！我是AI排班助手，我可以帮助您快速生成智能排班。\n\n请告诉我您的排班需求，例如：\n• 为特定医生生成排班\n• 为整个科室生成周期排班\n• 基于特定规则生成排班\n\n我已经加载了系统数据，可以为您提供准确的排班建议。",
    timestamp: new Date(),
  },
]);

// ==================== 生成数据 ====================
const generatedData = ref(null);

// ==================== 系统提示词 ====================
const SYSTEM_PROMPT = {
  role: "system",
  content: `你是一个专业的医院排班助手。请根据用户需求生成合理的排班安排。

系统数据：
- 科室：${props.departmentOptions.map(d => d.label).join(', ')}
- 人员类型：${props.staffTypeOptions.map(s => s.label).join(', ')}
- 班次：${props.timeSlotList.map(t => t.slot_name).join(', ')}
- 排班类型：${props.scheduleTypeList.map(s => s.type_name).join(', ')}
- 可用模板：${props.scheduleTemplates.map(t => t.template_name).join(', ')}

请基于以下排班模板生成合理的排班安排：
${props.scheduleTemplates.map(template => `
模板名称：${template.template_name}
适用科室：${template.department_name}
人员类型：${template.staff_type}
排班类型：${template.schedule_type}
班次安排：${template.time_slots}
规则说明：${template.rules || '无'}
`).join('\n')}

请以JSON格式返回排班数据，包含以下字段：
{
  "instances": [
    {
      "staff_id": "人员ID",
      "staff_name": "人员姓名", 
      "schedule_date": "YYYY-MM-DD",
      "time_slot_code": "班次代码",
      "schedule_type": "排班类型代码",
      "department_id": "科室ID",
      "department_name": "科室名称"
    }
  ],
  "overwriteStrategy": "skip|overwrite|merge",
  "notes": "排班说明",
  "template_based": true,  // 新增：标记是否基于模板
  "template_name": "使用的模板名称"  // 新增：使用的模板
}

请确保排班数据合理且符合医疗行业规范，只能使用匹配的模板规则。`
};

// ==================== 计算属性 ====================
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit("update:visible", value),
});

const resultStatus = computed(() => {
  if (!generatedData.value) {
    return { type: "info", text: "等待生成" };
  }
  return { type: "success", text: "已生成" };
});

// 计算系统数据统计信息
const systemDataStats = computed(() => {
  return {
    departments: props.departmentOptions.length,
    staffTypes: props.staffTypeOptions.length,
    timeSlots: props.timeSlotOptions.length,
    scheduleTypes: props.scheduleTypeOptions.length,
    totalStaff: props.allStaffList.length,
    currentSchedules: props.currentScheduleInstances.length,
  };
});

// ==================== 方法 ====================

/**
 * 格式化消息内容（支持简单换行）
 */
const formatMessage = (content) => {
  return content.replace(/\n/g, "<br>");
};

/**
 * 格式化时间显示
 */
const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleTimeString("zh-CN", {
    hour: "2-digit",
    minute: "2-digit",
  });
};

/**
 * 格式化覆盖策略
 */
const formatOverwriteStrategy = (strategy) => {
  const strategyMap = {
    skip: "跳过已有",
    overwrite: "覆盖已有",
    merge: "合并",
  };
  return strategyMap[strategy] || strategy;
};

/**
 * 格式化班次时间
 */
const formatTimeSlot = (slotCode) => {
  // 优先使用传入的timeSlotList数据
  const slotConfig = props.timeSlotList.find(
    (item) => item.slot_code === slotCode
  );
  if (slotConfig) {
    return slotConfig.slot_name;
  }
  return slotCode;
};

/**
 * 格式化排班类型
 */
const formatScheduleType = (typeCode) => {
  const typeConfig = props.scheduleTypeList.find(
    (item) => item.type_code === typeCode
  );
  return typeConfig ? typeConfig.type_name : typeCode;
};

/**
 * 根据人员ID获取人员信息
 */
const getStaffInfo = (staffId) => {
  return props.allStaffList.find((staff) => staff.id === staffId) || null;
};

/**
 * 根据科室ID获取科室信息
 */
const getDepartmentInfo = (departmentId) => {
  return (
    props.departmentList.find((dept) => dept.department_id === departmentId) ||
    null
  );
};

// ========================= AI智能排班 - 真实API调用 =============================
/**
 * 发送消息给AI
 */
const handleSendMessage = async () => {
  if (!userInput.value.trim() || loading.value) return;

  const userMessage = {
    role: "user",
    content: userInput.value,
    timestamp: new Date(),
  };

  // 添加用户消息
  chatMessages.value.push(userMessage);
  const currentInput = userInput.value;
  userInput.value = "";

  // 显示加载状态
  loading.value = true;
  isStoppedByUser.value = false;
  aiResponseBuffer.value = "";

  try {
    // 使用真实的AI API调用
    await callAIScheduleAPI(currentInput);
  } catch (error) {
    console.error("AI对话失败:", error);
    addAIMessage("抱歉，我遇到了一些问题。请稍后重试或检查网络连接。");
    loading.value = false;
  }
};

/**
 * 调用真实的AI排班API
 */
const callAIScheduleAPI = async (userInput) => {
  // 构建对话历史
  const messages = [
    SYSTEM_PROMPT,
    ...chatMessages.value
      .filter(msg => msg.role !== 'system')
      .map(msg => ({
        role: msg.role,
        content: msg.content
      }))
  ];

  // 添加当前用户输入
  messages.push({
    role: "user",
    content: `${userInput}\n\n请基于系统数据生成排班安排，并以JSON格式返回结果。`
  });

  // 添加AI消息占位符
  chatMessages.value.push({
    role: "assistant",
    content: "",
    timestamp: new Date(),
  });

  scrollToBottom();

  try {
    const response = await fetch("http://localhost:8000/v1/chat/completions", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        messages: messages,
        max_tokens: 2048,
        temperature: 0.1,
        stream: true,
      }),
    });

    if (!response.body) {
      throw new Error("服务器未返回流数据");
    }

    const reader = response.body.getReader();
    aiStreamReader.value = reader;
    const decoder = new TextDecoder("utf-8");
    let buffer = "";

    while (true) {
      if (isStoppedByUser.value) {
        await reader.cancel();
        break;
      }

      const { done, value } = await reader.read();
      if (done) {
        break;
      }

      const chunk = decoder.decode(value, { stream: true });
      buffer += chunk;

      const lines = buffer.split("\n");
      buffer = lines.pop();

      for (const line of lines) {
        if (line.startsWith("data: ")) {
          const jsonStr = line.slice(6).trim();
          if (jsonStr !== "[DONE]") {
            try {
              const jsonData = JSON.parse(jsonStr);
              const content = jsonData?.choices[0]?.delta?.content || "";
              
              if (content) {
                aiResponseBuffer.value += content;
                const lastMsg = chatMessages.value[chatMessages.value.length - 1];
                lastMsg.content += content;
                scrollToBottom();

                // 尝试解析JSON数据
                tryParseScheduleData(aiResponseBuffer.value);
              }
            } catch (error) {
              console.error("解析 JSON 数据失败:", error, line);
            }
          } else {
            // 流式传输完成
            finalizeAIMessage();
          }
        }
      }
    }
  } catch (error) {
    console.error("AI API调用失败:", error);
    if (!isStoppedByUser.value) {
      addAIMessage("抱歉，AI服务暂时不可用，请稍后重试。");
    }
  } finally {
    if (!isStoppedByUser.value) {
      loading.value = false;
    }
    aiStreamReader.value = null;
  }
};

/**
 * 尝试解析排班数据
 */
const tryParseScheduleData = (content) => {
  // 查找JSON开始和结束位置
  const jsonStart = content.indexOf('{');
  const jsonEnd = content.lastIndexOf('}') + 1;
  
  if (jsonStart !== -1 && jsonEnd > jsonStart) {
    try {
      const jsonStr = content.substring(jsonStart, jsonEnd);
      const scheduleData = JSON.parse(jsonStr);
      
      // 验证数据结构
      if (scheduleData.instances && Array.isArray(scheduleData.instances)) {
        // 补充完整数据
        const enhancedInstances = scheduleData.instances.map(instance => ({
          ...instance,
          create_by: "AI系统",
          status: 1,
          staff_name: instance.staff_name || getStaffInfo(instance.staff_id)?.name || "未知人员",
          department_name: instance.department_name || getDepartmentInfo(instance.department_id)?.department_name || "未知科室"
        }));
        
        generatedData.value = {
          ...scheduleData,
          instances: enhancedInstances,
          created_by: "AI系统"
        };
      }
    } catch (error) {
      // JSON解析失败，继续等待更多数据
    }
  }
};

/**
 * 完成AI消息处理
 */
const finalizeAIMessage = () => {
  const lastMsg = chatMessages.value[chatMessages.value.length - 1];
  if (lastMsg && lastMsg.content.trim()) {
    lastMsg.isCompleted = true;
    
    // 最终尝试解析排班数据
    if (!generatedData.value) {
      tryParseScheduleData(aiResponseBuffer.value);
    }
    
    if (generatedData.value) {
      lastMsg.content += `\n\n✅ 已成功生成 ${generatedData.value.instances.length} 条排班数据！\n请查看右侧的排班结果，确认无误后点击"确认生成排班"按钮。`;
    }
  }
  
  loading.value = false;
  scrollToBottom();
};

/**
 * 停止AI输出
 */
const stopOutput = async () => {
  if (!loading.value) return;

  isStoppedByUser.value = true;
  loading.value = false;

  if (aiStreamReader.value) {
    await aiStreamReader.value.cancel();
  }

  const lastMsg = chatMessages.value[chatMessages.value.length - 1];
  if (lastMsg) {
    lastMsg.isStopped = true;
    
    // 即使被停止，也尝试解析已接收的数据
    if (aiResponseBuffer.value) {
      tryParseScheduleData(aiResponseBuffer.value);
    }
  }

  // 调用停止生成接口
  try {
    await fetch("http://localhost:8000/api/stop_generation", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ confirm: true }),
    });
  } catch (error) {
    console.error("停止生成请求失败:", error);
  }
};

/**
 * 添加AI消息
 */
const addAIMessage = (content) => {
  chatMessages.value.push({
    role: "assistant",
    content: content,
    timestamp: new Date(),
  });
  scrollToBottom();
};

/**
 * 滚动到底部
 */
const scrollToBottom = () => {
  nextTick(() => {
    if (messageListRef.value) {
      messageListRef.value.scrollTop = messageListRef.value.scrollHeight;
    }
  });
};

/**
 * 清空对话
 */
const clearChat = () => {
  chatMessages.value = [
    {
      role: "assistant",
      content:
        "您好！我是AI排班助手，我可以帮助您快速生成智能排班。\n\n请告诉我您的排班需求，例如：\n• 为特定医生生成排班\n• 为整个科室生成周期排班\n• 基于特定规则生成排班\n\n我已经加载了系统数据，可以为您提供准确的排班建议。",
      timestamp: new Date(),
    },
  ];
  generatedData.value = null;
  userInput.value = "";
  aiResponseBuffer.value = "";
};

/**
 * 重新生成
 */
const handleRegenerate = () => {
  if (chatMessages.value.length > 1) {
    const lastUserMessage = chatMessages.value
      .filter((msg) => msg.role === "user")
      .pop();
    if (lastUserMessage) {
      userInput.value = lastUserMessage.content;
      handleSendMessage();
    }
  }
};

/**
 * 确认生成排班
 */
const handleConfirm = async () => {
  if (!generatedData.value) {
    ElMessage.warning("没有可确认的排班数据");
    return;
  }

  try {
    confirmLoading.value = true;

    // 将生成的排班数据传递给父组件
    emit("confirm", generatedData.value);

    ElMessage.success("排班数据已提交");
    dialogVisible.value = false;

    // 重置状态
    setTimeout(() => {
      clearChat();
    }, 300);
  } catch (error) {
    console.error("提交排班数据失败:", error);
    ElMessage.error("提交失败，请重试");
  } finally {
    confirmLoading.value = false;
  }
};

/**
 * 取消操作
 */
const handleCancel = () => {
  dialogVisible.value = false;
  emit("cancel");
};

/**
 * 重置状态
 */
const resetState = () => {
  clearChat();
  generatedData.value = null;
  loading.value = false;
  confirmLoading.value = false;
  isStoppedByUser.value = false;
  aiResponseBuffer.value = "";
};

// 在组件挂载时检查数据
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      resetState();
      // 可以在这里添加数据验证
      if (props.allStaffList.length === 0) {
        addAIMessage(
          "⚠️ 系统数据加载中，部分功能可能受限。请确保父组件已正确加载人员数据。"
        );
      }
    }
  }
);

defineExpose({
  resetState,
});
</script>

<style scoped lang="scss">
.ai-schedule-generator {
  height: 500px;
  display: flex;
  flex-direction: column;
}

.ai-layout {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  height: 100%;
  min-height: 0; /* 重要：防止网格项溢出 */
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;

  h3 {
    margin: 0;
    color: #303133;
    font-size: 16px;
    font-weight: 600;
  }
}

/* 聊天区域样式 */
.ai-chat-section {
  display: flex;
  flex-direction: column;
  border-right: 1px solid #ebeef5;
  padding-right: 20px;
  height: 100%;
  min-height: 0; /* 重要：防止内容溢出 */
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0; /* 重要：允许内部元素滚动 */
  height: 100%;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px 4px 8px 0;
  margin-bottom: 16px;
  min-height: 0;
  max-height: calc(100% - 120px); /* 为输入区域预留空间 */

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
  }
}

.message-item {
  display: flex;
  margin-bottom: 16px;
  animation: fadeIn 0.3s ease-out;

  &.user {
    flex-direction: row-reverse;

    .message-content {
      margin-left: 0;
      margin-right: 12px;
      align-items: flex-end;
    }

    .message-text {
      background: #1890ff;
      color: white;
      border-radius: 12px 12px 4px 12px;
    }
  }

  &.assistant {
    .message-content {
      margin-left: 12px;
      margin-right: 0;
      align-items: flex-start;
    }

    .message-text {
      background: #f5f7fa;
      color: #303133;
      border-radius: 12px 12px 12px 4px;
    }
  }
}

.message-avatar {
  flex-shrink: 0;
}

.message-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  max-width: calc(100% - 50px); /* 为头像预留空间 */
  min-width: 0; /* 重要：防止文本溢出 */
}

.message-text {
  padding: 12px 16px;
  line-height: 1.5;
  word-wrap: break-word;
  word-break: break-word; /* 重要：长单词换行 */
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  overflow-wrap: break-word; /* 兼容性 */
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  flex-shrink: 0; /* 防止时间戳被挤压 */
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 4px;

  span {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background: #909399;
    animation: typing 1.4s infinite ease-in-out;

    &:nth-child(1) {
      animation-delay: -0.32s;
    }
    &:nth-child(2) {
      animation-delay: -0.16s;
    }
  }
}

@keyframes typing {
  0%,
  80%,
  100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.input-section {
  flex-shrink: 0; /* 防止输入区域被压缩 */
  margin-top: auto; /* 推到容器底部 */

  .ai-loading {
    font-size: 13px;
    color: #666;
    text-align: center;
    margin-bottom: 8px;
  }

  .input-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 8px;
    margin-top: 12px;
  }
}

/* 结果区域样式 */
.result-section {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
}

.result-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  height: 100%;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  text-align: center;
  flex: 1;

  p {
    margin-top: 12px;
    font-size: 14px;
  }
}

.result-preview {
  height: 100%;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  flex-shrink: 0;

  h4 {
    margin: 0;
    color: #303133;
    font-size: 15px;
  }
}

.preview-content {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 16px;
  min-height: 0;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
  }
}

.schedule-preview {
  margin-top: 16px;

  h5 {
    margin: 0 0 12px 0;
    color: #606266;
    font-size: 14px;
    font-weight: 600;
  }
}

.preview-list {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  max-height: 200px;
  overflow-y: auto;
}

.preview-item {
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }
}

.preview-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 8px;

  .staff-name {
    font-weight: 500;
    color: #303133;
    flex-shrink: 0;
  }

  .schedule-date {
    color: #606266;
    font-size: 13px;
    flex: 1;
    text-align: center;
  }
}

.preview-more {
  padding: 12px;
  text-align: center;
  color: #909399;
  font-size: 13px;
  background: #fafafa;
}

.confirm-actions {
  flex-shrink: 0; /* 防止确认区域被压缩 */
  margin-top: auto; /* 推到容器底部 */

  .action-buttons {
    display: flex;
    gap: 8px;
    margin-top: 16px;

    .el-button {
      flex: 1;
    }
  }
}

/* 发送按钮样式 */
.ds-button-area {
  white-space: nowrap;
}

.send-area {
  white-space: nowrap;
  cursor: pointer;
  color: #fff;
  background: #4d6bfe;
  border: none;
  border-radius: 6px;
  flex-direction: column;
  flex-shrink: 0;
  justify-content: center;
  align-items: center;
  min-width: 32px;
  height: 32px;
  display: flex;
}

.send-area:hover {
  background: #2563eb;
}

.ds-icon {
  font-size: 16px;
  width: 16px;
  height: 16px;
}

.ds-icon svg {
  width: 100%;
  height: 100%;
}

.ds-icon-stop {
  width: 12px;
  height: 12px;
  background: rgb(252, 250, 250);
  border-radius: 2px;
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .ai-layout {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .ai-chat-section {
    border-right: none;
    padding-right: 0;
    border-bottom: 1px solid #ebeef5;
    padding-bottom: 16px;
    height: 300px; /* 移动端固定高度 */
  }

  .message-content {
    max-width: 85%;
  }

  .message-list {
    max-height: calc(100% - 100px);
  }
}

/* 对话框内容区域样式修复 */
:deep(.el-dialog__body) {
  padding: 20px;
  height: 500px;
  min-height: 500px;
}

/* 确保文本区域不会过度增长 */
:deep(.el-textarea__inner) {
  resize: none;
  min-height: 60px;
  max-height: 100px;
}
</style>